# _*_ encoding: utf-8 _*_
# __author__ = 'lx'
import json
import platform
from argparse import Namespace
import requests
# import aiohttp
from urllib.parse import urlencode

OS_SYSTEM = platform.system().lower()


class RequestBase:
    APIs = {}
    api_key = None

    def set_api_key(self, api_key):
        self.api_key = api_key
        return True

    def get_api_key(self):
        return self.api_key

    def get_api(self, api_name):
        return self.APIs[api_name]

    @staticmethod
    def json_to_object_or_dict(json_data, flag='dict'):
        if flag == 'dict':
            x = json.loads(json_data)
        else:
            x = json.loads(json_data, object_hook=lambda d: Namespace(**d))
        return x

    def api_request(self, url, parameters):
        parameters['key'] = self.api_key
        # urllib3==1.25.11时不需要改变代理，非win系统也不用改变代理
        if OS_SYSTEM == "windows":
            proxies = {
                'http': 'http://127.0.0.1:10809',
                'https': 'http://127.0.0.1:10809'  # https -> http
            }
            response = requests.get(url, params=parameters, timeout=5, proxies=proxies)
        else:
            response = requests.get(url, params=parameters, timeout=5)
        data = response.text

        youtube_object = self.json_to_object_or_dict(data)
        return youtube_object

    # async def async_request(self, url, parameters):
    #     parameters['key'] = self.api_key
    #
    #     req_url = url + '?' + urlencode(parameters)
    #     async with aiohttp.request('GET', req_url) as response:
    #         data = await response.json()
    #
    #     youtube_object = self.json_to_object_or_dict(data)
    #     return youtube_object